<template>
  <el-main>
<!--    新建用户对话框-->
    <el-dialog v-model="isFlag.dialogVisbaleCreateUser"  title="新建用户" width="500" center>
      <el-form :model="newUser">
        <el-form-item label="账号:">
          <el-input v-model="newUser.username" placeholder="账号不能为空"
          ></el-input>
        </el-form-item>
        <el-form-item label="名称:">
          <el-input v-model="newUser.nickname" placeholder="名称不能为空"></el-input>
        </el-form-item>
        <el-form-item label="密码:">
          <el-input v-model="newUser.password"></el-input>
        </el-form-item>
        <el-form-item label="电话:">
          <el-input v-model="newUser.phone"></el-input>
        </el-form-item>
        <el-form-item label="类型:">
          <el-input v-model="newUser.type" placeholder="负责类型不能为空"></el-input>
        </el-form-item>
        <el-form-item label="职业:">
          <el-select v-model="newUser.job" placeholder="请选择" size="large" style="width: 240px">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isFlag.dialogVisbaleCreateUser = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>
<!--    编辑用户对话框-->
    <el-dialog v-model="isFlag.dialogVisbaleEditUser"  title="编辑用户" width="500" center>
      <el-form :model="currentUser">
        <el-form-item label="账号:">
          <el-input v-model="currentUser.username" placeholder="账号不能为空"> </el-input>
        </el-form-item>
        <el-form-item label="名称:">
          <el-input v-model="currentUser.nickname" placeholder="名称不能为空"></el-input>
        </el-form-item>
        <el-form-item label="密码:">
          <el-input v-model="currentUser.password"></el-input>
        </el-form-item>
        <el-form-item label="电话:">
          <el-input v-model="currentUser.phone"></el-input>
        </el-form-item>
        <el-form-item label="类型:">
          <el-input v-model="currentUser.type" placeholder="负责类型不能为空"></el-input>
        </el-form-item>
        <el-form-item label="职业:">
          <el-select v-model="currentUser.job" placeholder="请选择" size="large" style="width: 240px" >
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.label"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isFlag.dialogVisbaleEditUser = false">取消</el-button>
          <el-button type="primary" @click="Edit(currentUser)">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <div class="w-full flex flex-row gap-2 border-b-gray-300 border p-2">
      <el-input v-model="searchQuery" placeholder="用户" class="max-w-[200px]" ></el-input>
        <el-select v-model="FilterJob"  placeholder="职业" style="width: 200px"  >
          <el-option
              v-for="item in joboptions"
              :key="item.value"
              :label="item.label"
              :value="item.label"
          />
        </el-select>
      <div>
        <el-button type="success" @click="FilterUsers()">查询</el-button>
        <el-button type="danger" @click="FilterReset()">重置</el-button>
        <el-button @click="handeladd" type="primary">添加用户</el-button>
      </div>
    </div>
    <el-table v-if="userslist" :data="userslist" style="width: 100%">
      <el-table-column prop="id" label="编号"  />
      <el-table-column prop="nickname" label="姓名"  />
      <el-table-column prop="role" label="权限等级"  />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="job" label="职业" />
        <el-table-column prop="type" label="主科" />
      <el-table-column label="操作">
        <template #default="scope">
          <div class="flex flex-row gap-1 w-[200px]">
            <button v-if="scope.row.role!=='4'"
                class="bg-element-green text-white px-2.5 py-1 rounded-md hover:bg-element-hover-green"
                @click="handleEdit(scope.row)">
                编辑
            </button>
            <el-popconfirm
                confirm-button-text="是"
                cancel-button-text="否"
                icon-color="#626AEF"
                title="你确认要删除吗？"
                @confirm="confirmEvent(scope.row)"
            >
              <template #reference>
                <button  v-if="scope.row.role!=='4'" class="bg-red-500 text-white px-2.5 py-1 rounded-md hover:bg-red-600">删除</button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

  </el-main>
</template>
<script setup lang="ts">
import {ElMessage} from "element-plus";
import {onMounted,ref, reactive} from "vue";
import axios, {request} from "axios";


const options = [
  {
    value: '3',
    label: '管理员',
  },
  {
    value: '2',
    label: '饲养员',
  },
  {
    value: '1',
    label: '医生',
  },
]
const joboptions = [
  {
    value:'1',
    label:'医生',
  },
  {
    value:'2',
    label:'饲养员',
  },
  {
    value:'3',
    label:'管理员',
  },
  {
    value:'4',
    label:'超级管理员',
  }
]
const userslist = ref([])
const searchQuery = ref();
const FilterJob =ref();
const filteredList = ref([]);
const isFlag = reactive({
  dialogVisbaleCreateUser: false,
  dialogVisbaleEditUser: false,
})

class NewUser {
  constructor(
      public username: string = '',
      public password: string = '',
      public nickname: string = '',
      public role: number = 1,
      public phone: string = '',
      public type: string = '',
      public job: string = ''
  ) {}
}
let newUser = reactive(new NewUser());
const currentUser = reactive({});
const pageTotal = ref(30);
const pageSize =ref(10);
const pageCurrent =ref(1);

function handeladd(){
  isFlag.dialogVisbaleCreateUser = true;
  newUser = reactive(new NewUser());
}
// 表单验证函数，确保名称和体重不为空且不包含特殊字符

function validateForm(tmpAnimal): boolean {
    if (tmpAnimal.username.trim() === '' ) {
        showErrorMessage('账号不能为空');
        return false;
    }
    if (checkSpecialCharacters(tmpAnimal.username)) {
        showErrorMessage('账号不能包含特殊字符');
        return false;
    }
    if (String(tmpAnimal.nickname).trim() === '') {
        showErrorMessage('名称不能为空');
        return false;
    }
    if (checkSpecialCharacters(String(tmpAnimal.nickname))) {
        showErrorMessage('名称不能包含特殊字符');
        return false;
    }
    if (String(tmpAnimal.type).trim() === '') {
        showErrorMessage('负责种类不能为空');
        return false;
    }
    if (checkSpecialCharacters(String(tmpAnimal.type)) ){
        showErrorMessage('负责种类不能为特殊字符');
        return false;
    }
    return true;
}

// 检查字符串是否包含特殊字符的函数
function checkSpecialCharacters(input: string): boolean {
    // 此处可以根据需要定义特殊字符的规则，例如只允许中英文和数字，不允许特殊符号等
    const pattern = /[!@#$%^&*()+\=\[\]{};':"\\|,.<>\/?~]/;
    return pattern.test(input);
}

// 显示错误信息的弹窗
function showErrorMessage(message: string) {
    ElMessageBox.alert(message, '提示', {
        confirmButtonText: '确定',
    });
}

function save(){
    if (!validateForm(newUser)) {
        return; // 如果表单验证不通过，直接返回，不继续保存操作
    }
    if(newUser.job==3){
        newUser.role=3
    }
  axios.post('http://localhost:8080/user/save',newUser)
      .then(request =>{
        if (request.data){
          ElMessage({
            message:'添加成功',
            type:'success'
          })
          init();
          isFlag.dialogVisbaleCreateUser = false;

        }
      })
      .catch(error => {
          console.error('保存失败：', error);
          ElMessage({
              message: '保存失败，请重试',
              type: 'error'
          });
      });
}
function init(){
  axios.get('http://localhost:8080/user/getlist')
      .then(request =>{
        //console.log(request)
        userslist.value = request.data
        filteredList.value = request.data
        console.log(userslist+"我我我我问");
         //Object.assign(filteredList,request.data)
      })
  console.log("测试执行")


    console.log(filteredList)
}
init()

function handleEdit (user){
  Object.assign(currentUser,user)
  isFlag.dialogVisbaleEditUser = true;
  console.log(currentUser)
}
function Edit(){
    if (!validateForm(currentUser)) {
        return; // 如果表单验证不通过，直接返回，不继续保存操作
    }
    axios.post('http://localhost:8080/user/update',currentUser)
        .then(request =>{
            console.log(request.data)
            if (request.data){
                ElMessage({
                    message:'修改成功',
                    type:'success'
                })
                init();
                isFlag.dialogVisbaleEditUser = false;

            }
        })
        .catch(error => {
            console.error('保存失败：', error);
            ElMessage({
                message: '保存失败，请重试',
                type: 'error'
            });
        });

  }
function confirmEvent(currentUser) {
  console.log('confirm!')
  axios.post('http://localhost:8080/user/remove',currentUser)
      .then(request =>{
        console.log(request.data)
        if (request.data){
          ElMessage({
            message:'删除成功',
            type:'success'
          })
          init();
        }
      })
}


function FilterUsers (){
  axios.get('http://localhost:8080/user/getlist')
      .then(request =>{
        filteredList.value = request.data
        if(FilterJob.value!=null){
          filteredList.value=filteredList.value.filter(item =>item.job === FilterJob.value)}
        if(searchQuery.value!=null){
          filteredList.value=filteredList.value.filter(item => {
            return item.nickname.includes(searchQuery.value);
          });}
        userslist.value=filteredList.value;
      })
  console.log(filteredList)
}
function FilterReset(){
  location.reload();
}




</script>
